import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io' show Platform;
import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import '../config/app_config.dart';
import '../models/api_response.dart';

class AuthService {
  // API服务器地址
  static String get baseUrl {
    // 移除api后缀，因为AppConfig.apiServerUrl已经包含
    return AppConfig.apiServerUrl.replaceAll('/api', '');
  }

  // token存储键名
  static const String accessTokenKey = 'access_token';
  static const String refreshTokenKey = 'refresh_token';
  static const String userIdKey = 'user_id';
  static const String usernameKey = 'username';
  static const String emailKey = 'email';

  // 用户注册
  static Future<ApiResponse<void>> register({
    required String username,
    required String email,
    required String password,
  }) async {
    var uri = Uri.parse('$baseUrl/auth/register');

    try {
      var response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'username': username,
          'email': email,
          'password': password,
        }),
      );

      final responseData = json.decode(utf8.decode(response.bodyBytes));
      final apiResponse = ApiResponse<void>.fromJson(responseData, null);

      if (apiResponse.isSuccess) {
        return apiResponse;
      } else {
        throw Exception(apiResponse.message);
      }
    } catch (e) {
      throw Exception('注册请求出错: $e');
    }
  }

  // 用户登录
  static Future<ApiResponse<AuthResponse>> login({
    required String username,
    required String password,
  }) async {
    var uri = Uri.parse('$baseUrl/auth/login');

    try {
      final client = http.Client();
      final response = await client
          .post(
            uri,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: {'username': username, 'password': password},
          )
          .timeout(
            const Duration(seconds: 15),
            onTimeout: () {
              client.close();
              throw TimeoutException('登录请求超时，请检查网络连接后重试');
            },
          );

      client.close();

      final responseData = json.decode(utf8.decode(response.bodyBytes));
      print('登录响应数据: $responseData');

      final apiResponse = ApiResponse<AuthResponse>.fromJson(
        responseData,
        (data) => AuthResponse.fromJson(data),
      );

      print('解析后的响应: ${apiResponse.data?.user.id}');

      if (apiResponse.isSuccess && apiResponse.data != null) {
        // 保存认证信息
        await _saveAuthData(apiResponse.data!);
        print('登录成功：${apiResponse.data!.accessToken}');
        return apiResponse;
      } else {
        throw Exception(apiResponse.message);
      }
    } on TimeoutException catch (e) {
      print('登录超时：$e');
      throw Exception('登录超时，请检查网络连接后重试');
    } catch (e) {
      print('登录错误：$e');
      throw Exception('登录请求出错: $e');
    }
  }

  // 保存认证数据
  static Future<void> _saveAuthData(AuthResponse authData) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(userIdKey, authData.user.id);
    await prefs.setString(accessTokenKey, authData.accessToken);
    await prefs.setString(refreshTokenKey, authData.refreshToken);
    await prefs.setString(usernameKey, authData.user.username);
    await prefs.setString(emailKey, authData.user.email);
  }

  // 刷新token
  static Future<bool> refreshToken() async {
    final prefs = await SharedPreferences.getInstance();
    final refreshToken = prefs.getString(refreshTokenKey);

    if (refreshToken == null) {
      return false;
    }

    try {
      final response = await http.post(
        Uri.parse('$baseUrl/auth/refresh'),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({'refresh_token': refreshToken}),
      );

      final responseData = json.decode(utf8.decode(response.bodyBytes));
      final apiResponse = ApiResponse<AuthResponse>.fromJson(
        responseData,
        (data) => AuthResponse.fromJson(data),
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        await _saveAuthData(apiResponse.data!);
        return true;
      }
    } catch (e) {
      print('刷新token失败：$e');
    }

    return false;
  }

  // 获取访问token
  static Future<String?> getAccessToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(accessTokenKey);
  }

  // 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final token = await getAccessToken();
    return token != null && token.isNotEmpty;
  }

  // 获取用户ID
  static Future<int?> getUserId() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt(userIdKey);
  }

  // 获取用户名
  static Future<String?> getUsername() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(usernameKey);
  }

  // 获取邮箱
  static Future<String?> getEmail() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(emailKey);
  }

  // 退出登录
  static Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(accessTokenKey);
    await prefs.remove(refreshTokenKey);
    await prefs.remove(userIdKey);
    await prefs.remove(usernameKey);
    await prefs.remove(emailKey);
  }

  // 获取认证头信息
  static Future<Map<String, String>> getAuthHeaders() async {
    final token = await getAccessToken();
    if (token == null || token.isEmpty) {
      return {};
    }
    return {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    };
  }

  // 处理认证错误
  static Future<bool> handleAuthError(int statusCode) async {
    if (statusCode == 401) {
      // token过期，尝试刷新
      return await refreshToken();
    }
    return false;
  }
}
